<?php
namespace app\common\controller;


use think\Config as ThinkConfig;
use think\Request;
use think\Response;
use think\response\Redirect;
use think\exception\HttpResponseException;
use think\View as ThinkView;

class   Base
{
    /**
     * @var \think\Request 请求对象
     */
    protected $request;
    /**
     * @var \think\View 视图类实例
     */
    protected $view;

    const CODE_ILL = -1;
    const CODE_SUS = 1;
    const CODE_FAIL = 0;

    public function __construct()
    {
        $this->request = Request::instance();
        $this->view = ThinkView::instance(ThinkConfig::get('template'), ThinkConfig::get('view_replace_str'));
    }

    /**
     * 模板变量赋值
     * @access protected
     * @param mixed $name  要显示的模板变量
     * @param mixed $value 变量的值
     * @return void
     */
    protected function assign($name, $value = '')
    {
        $this->view->assign($name, $value);
    }


    /**
     * 加载模板输出
     * @access protected
     * @param string $template 模板文件名
     * @param array  $vars     模板输出变量
     * @param array  $replace  模板替换
     * @param array  $config   模板参数
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        return $this->view->fetch($template, $vars, $replace, $config);
    }

    protected function jsonFail($msg, $data=[]){
        return Response::create(['code'=>self::CODE_FAIL, 'msg'=>$msg, 'data'=>$data], 'json');
    }

    protected function jsonSuccess($msg, $data=[]){
        return Response::create(['code'=>self::CODE_SUS, 'msg'=>$msg, 'data'=>$data], 'json');
    }

    protected function json(array $data){
        return Response::create($data, 'json');
    }

    /**
     * URL重定向
     * @access protected
     * @param string         $url 跳转的URL表达式
     * @param array|integer  $params 其它URL参数
     * @param integer        $code http code
     * @param array          $with 隐式传参
     * @return void
     */
    protected function redirect($url, $params = [], $code = 302, $with = [])
    {
        $response = new Redirect($url);
        if (is_integer($params)) {
            $code   = $params;
            $params = [];
        }
        $response->code($code)->params($params)->with($with);
        throw new HttpResponseException($response);
    }
}
